import org.jenkinsci.plugins.scriptsecurity.scripts.*
import jenkins.model.Jenkins

def jenkins = Jenkins.instance


//获取视图列表
def viewPath = "${WORKSPACE}/views"
def viewFolder = new File("${viewPath}")
def viewNames = []
viewFolder.eachFile { file -> viewNames.add(file.name) }
println "Found views: ${viewNames}"

viewNames.each { viewName ->
    println "Processing view: ${viewName}"
    
    // 检查视图目录是否存在
    def viewDir = new File("${viewPath}/${viewName}")
    if (!viewDir.exists() || !viewDir.isDirectory()) {
        println "视图目录不存在或不是一个目录，跳过处理：${viewName}"
        return
    }
  	def jobFolder = new File("${viewPath}/${viewName}")
	def jobNames = []
    jobFolder.eachFile { file -> jobNames.add(file.name) }
    println "Found jobs in view '${viewName}': ${jobNames}"

  	//遍历处理Job更新
    jobNames.each { jobName ->
        println "Processing job: ${jobName}"
        //处理Job
        def paramPath = "${viewPath}/${viewName}/${jobName}/parameters.groovy"
        def pipelinePath = "${viewPath}/${viewName}/${jobName}/Jenkinsfile.groovy"
        if (!new File(paramPath).exists() || !new File(pipelinePath).exists()) {
            println "参数文件或Jenkinsfile不存在，跳过处理：${jobName}"
            return
        }
        def paramClosure = evaluate(new File("${viewPath}/${viewName}/${jobName}/parameters.groovy").getText('UTF-8'))
        def pipelineContent = new File("${viewPath}/${viewName}/${jobName}/Jenkinsfile.groovy").text
        
        pipelineJob("${jobName}") {
            displayName("${jobName}")
            description("${jobName}")
    
            // 定义参数
            parameters(paramClosure)
    
            // 定义流水线
            definition {
                cps {
                    script("${pipelineContent}")
                    sandbox(true)
                }
            }
        }
  
        println "Finished processing job: ${jobName}"
    }
  
    // 创建或更新视图
    def view = jenkins.getView(viewName)
    if (view == null) {
        println("视图不存在，创建View并添加Job到View中！")
        listView(viewName) {
            description("视图包含所有Mobile测试相关的Job")
            jobs {
                jobNames.each { jobName ->
                    if(!jobName.startsWith(".")) {
                        name(jobName)
                    }
                }
            }
            columns {
                status()
                weather()
                name()
                lastSuccess()
                lastFailure()
                lastDuration()
                buildButton()
            }
        }
    } else {
        // 如果视图已存在，更新其中的Job列表
        println("视图已存在，添加Job到View中！")
        def listJobs = view.getJobNames()
        jobNames.each { jobName ->
            if(!jobName.startsWith(".")) {
                view.add(jenkins.getItem(jobName))
            }
        }
        view.save()
    }
}

import org.jenkinsci.plugins.scriptsecurity.scripts.*
  
//解决脚本执行权限问题
def approval = ScriptApproval.get()  
def pending = approval.getPendingScripts()
if(pending.size() == 0) {
	println "No pending scripts need to review."
	return
} 

//遍历输出
println "After pending scripts found: (${pending.size()})"
pending.eachWithIndex { script, i ->
    println "\n[${i+1}] Hash: ${script.hash}"
    println "Content (${script.script.length()} chars):"
    println "----------------------------------------"
    println script.script
    println "----------------------------------------"
}

//评审通过script
new ArrayList(pending).each { script ->
    approval.approveScript(script.hash)
}

pending = approval.getPendingScripts()
println "After pending Scripts size: (${pending.size()})"